import useDictStore from '@/store/modules/dict'
import { listDictData } from '@/api/system/dict/data'

/**
 * 获取字典数据
 * 1.获取字典管理的数据：proxy.useDict('sys_common_status')
 * 2.获取业务数据：proxy.useDict({
    key: 'product_attr', // store中存储的key
    request: listAttr, // 请求方法
    params: {}, // 请求参数 
    page: true // 是否分页请求，为true时会自动分页请求完所有数据返回
  })
 */
export function useDict (...args) {
  const res = ref({});
  const page = ref({
    currentPage: 1,
    pageSize: 100
  })
  return (async () => {
    return await new Promise(async (resolve, reject) => {
      await Promise.all(
        args.map(async (item) => {
          let dictType
          let request
          let params
          let isPage = false
          let formatter
          let _page = page.value
          if (item instanceof Object) {
            dictType = item.key
            if (item.request) {
              request = item.request
            }
            if (item.params && item.params instanceof Object) {
              params = item.params
            }
            isPage = !!item.page
            if (isPage) {
              if (item.page instanceof Object) {
                _page = item.page
              }
              params = {
                ...(params || {}),
                ..._page
              }
            }
            if (item.formatter && item.formatter instanceof Function) {
              formatter = item.formatter
            }
          } else {
            dictType = item
            request = listDictData
            params = { dictType }
          }
          const dicts = useDictStore().getDict(dictType);
          // 字典类型数据或指定缓存数据才读取缓存
          if (dicts && (typeof item === 'string' || item.cache !== false)) {
            res.value[dictType] = dicts;
          } else {
            let pageData = []
            const fetchData = (params) => {
              return new Promise(async (resolve, reject) => {
                try {
                  const response = await request(params)
                  if (!isPage) {
                    resolve(response?.data || [])
                  } else {
                    const data = response?.data?.records || (response && response.data instanceof Array ? response.data : [])
                    pageData = [...pageData, ...data]
                    if (((response?.data?.total || response?.total) || 0) > (_page.pageSize * params.currentPage)) {
                      params.currentPage++
                      await fetchData(params)
                    }
                    resolve(pageData)
                  }
                } catch (error) {
                  resolve([])
                }
              })
            }
            let data = await fetchData(params)
            data = (data || []).map(i => ({ ...i, label: i.dictLabel, value: i.dictValue  }))
            const resolveData = formatter && formatter instanceof Function ? formatter(data) : data
            res.value[dictType] = resolveData
            useDictStore().setDict(dictType, res.value[dictType], { args: item });
          }
        })
      )
      resolve(toRefs(res.value))
    })
  })()
}

export function updateDict (ref, prop, dicts) {
  if (ref && ref.updateDic) {
    Object.keys(dicts).forEach(_dictKey => {
      const updater = () => {
        const _value = useDictStore().getDict(_dictKey) || dicts[_dictKey]
        const _prop = prop
        const _ref = ref
        return (() => {
          _ref.updateDic(_prop, _value)
        })()
      }
      updater()
      useDictStore().setUpdater(_dictKey, updater)
    })
  }
}

export function refreshDict (...keys) {
  keys.forEach(key => {
    const dict_store = useDictStore().getDict(key)
    if (dict_store) {
      const { args } = useDictStore().dict.find(k => k.key === key) || {}
      if (args) {
        useDictStore().removeDict(key)
        useDict(args)
          .then(() => {
            useDictStore().getUpdater(key).forEach(updater => {
              updater()
            })
          })
      }
    }
  })
}